iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 58

[Day 57] Linked List Cycle II (Medium)

  • 分享至 

  • xImage
  •  

142. Linked List Cycle II

Solution 1: HashSet

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return None
        
        nodeSet = set()
        ptrA = head
        while ptrA:
            if ptrA in nodeSet:
                return ptrA
            nodeSet.add(ptrA)
            ptrA = ptrA.next
        
        return None

Time Complexity: O(N)
Space Complexity: O(N)

Solution 2: Floyd's Cycle Algorithm

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or head.next is None:
            return None
        
        ptrSlow = head
        ptrFast = head
        # Detect cycle
        while ptrFast and ptrFast.next:
            ptrSlow = ptrSlow.next
            ptrFast = ptrFast.next.next
            if ptrSlow == ptrFast:
                break
        if ptrFast is None or ptrFast.next is None:
            return None
        
        # Check the intersection
        ptrSlow = head
        while ptrSlow != ptrFast:
            ptrSlow = ptrSlow.next
            ptrFast = ptrFast.next

        return ptrSlow

Time Complexity: O(N)
Space Complexity: O(1)

Reference

https://leetcode.com/problems/linked-list-cycle-ii/discuss/1701055/JavaC%2B%2BPython-best-explanation-ever-happen's-for-this-problem
https://matthung0807.blogspot.com/2020/04/floyd-cycle-detection-algorithm-floyd.html
https://ithelp.ithome.com.tw/articles/10223721


上一篇
[Day 56] Sliding Window Maximum (Hard)
下一篇
[Day 58] Word Break (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言